﻿using System;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace QDP.Platform.Services
{
    /// <summary>提供服务加载的支持。</summary>
    public static class ServiceLoader
    {
        /// <summary>加载一个平台服务对象，若该服务对象不存在或未实例化则返回空。<para>使用时需要考虑返回值是否为空。</para></summary>
        /// <typeparam name="T">需要加载的服务类型</typeparam>
        /// <returns></returns>
        public static T Load<T>()
        {
            var v = from s in Q.WidgetManager.Widgets
                    where s.PartElement != null && s.PartElement.WidgetContent is T
                    select s.PartElement.WidgetContent;
            if (v.Count() > 0)
            {
                return (T)(v.First() as object);
            }
            else
            {
                var parts = from s in Q.WidgetManager.Widgets
                            where s.PartElement is T
                            select s.PartElement;
                if (parts.Count() > 0)
                {
                    return (T)(parts.First() as object);
                }
            }
            return default(T);
        }
        /// <summary>根据url地址创建一个指定类型的WCF服务客户端。</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T CreateWCFClient<T>(string url)
        {
            return CreateWCFClient<T>(new Uri(url));
        }
        /// <summary>根据url地址创建一个指定类型的WCF服务客户端。</summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uri"></param>
        /// <returns></returns>
        private static T CreateWCFClient<T>(Uri uri)
        {
            BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.None)
            {
                //MaxReceivedMessageSize = long.MaxValue,

                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferSize = int.MaxValue,
                SendTimeout = TimeSpan.FromMinutes(1),
                ReceiveTimeout = TimeSpan.FromMinutes(1),
                TransferMode =  TransferMode.Buffered,
            };
            CustomBinding binding = new CustomBinding(basicBinding);
            //binding.Elements.Add()
            EndpointAddress endPoint = new EndpointAddress(uri);

            object obj = Activator.CreateInstance(typeof(T), binding, endPoint);
            if (obj is T)
            {
                return (T)obj;
            }
            else
            {
                return default(T);
            }
        }
    }
}
